#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils.util import datetime_now_str
from controls.mongo import db_shitouren as db
from pymongo import DESCENDING
from pymongo import ASCENDING

# test start
# from pymongo import MongoClient
# client = MongoClient( etc.mongo_host, 27017 )
# db = client.test
# test end

# collection in mongodb
coll = db.app_ver
"""db.app_ver collection has
    appver:         app版本号 (str)
    ctime:          创建时间  (str)
    detail: [
        {
            path:           修改文件相对路径(str)
            filename:       修改文件名(str)
            optype:         文件操作类型(int) (1:增加，2:更新，3:删除)
            url:            文件服务器路径url(str)
        }
    ]
"""

'''
add app version update detail info
detail_list is a list
test method
'''


def get_detail_by_app_ver(appver):
    '''get detail modify by appver
    '''
    if not appver:
        return None
    cond = {}
    if appver: cond['appver'] = str(appver)
    res = coll.find_one(
        cond, {'_id': 0, 'appver': 1, 'detail': 1, 'ctime': 1}
    )  # .sort('ctime', ASCENDING).limit(nums)

    return res


'''
获取该版本之后的所有修改
不包含传入参数的版本
'''
def get_all_details_from_app_ver(appver):
    '''get latest modify content
    '''
    if not appver:
        return None

    num = turn_ver_to_int(appver)
    # get all greater than this version's num
    all_list = coll.find({'num': {'$gt': num}}, {'_id': 0, 'appver': 1, 'detail': 1, 'ctime': 1, 'num': 1}).sort('num',
                                                                                                                 ASCENDING)
    res_list = [{'ctime': item[u'ctime'].encode('utf-8'), 'appver': item[u'appver'].encode('utf-8'),
                 'detail': item[u'detail']} for item in all_list]

    return res_list


'''
add app version update detail info
detail_list is a list
'''


def add_detail_for_app_ver(appver, detail_list, ctime=None):
    '''add  modify details
    '''
    if not (appver and detail_list):
        return False
    cond = {}
    if appver: cond['appver'] = str(appver)
    exist = coll.find_one(cond, {'_id': 0, 'appver': 1, 'detail': 1, 'ctime': 1})
    # push
    if exist:
        for detail in detail_list:
            res = coll.update(cond, {'$push': {'detail': detail}}, True)
    else:
        # insert
        if not ctime:
            ctime = datetime_now_str()
        # num = coll.find().count() + 1
        num = turn_ver_to_int(appver)
        res = coll.insert({'num': num, 'appver': appver, 'detail': detail_list, 'ctime': ctime})

    return True


def turn_ver_to_int(appver):
    bigv, midv, smlv = appver.split('.')
    ver_int = int(bigv) * 10000000 + int(midv) * 10000 + int(smlv)
    return ver_int


if __name__ == "__main__":
    print 'main start'
    '''
    print '=============insert test data'
    add_detail_for_app_ver('2.1.1', [{'path': 'path1_1', 'filename': 'filename1_1', 'optype': '1', 'url': 'url1_1'}])
    add_detail_for_app_ver('2.1.1', [{'path': 'path1_2', 'filename': 'filename1_2', 'optype': '2', 'url': 'url1_2'}])
    add_detail_for_app_ver('2.1.2', [{'path': 'path2', 'filename': 'filename2', 'optype': '2', 'url': 'url2'}])
    add_detail_for_app_ver('2.1.7', [{'path': 'path7_1', 'filename': 'filename7_1', 'optype': '7_1', 'url': 'url7_1'},
                                     {'path': 'path7_2', 'filename': 'filename7_2', 'optype': '7_2', 'url': 'url7_2'}])
    add_detail_for_app_ver('2.1.7', [{'path': 'path7_6', 'filename': 'filename7_6', 'optype': '7_6', 'url': 'url7_6'},
                                     {'path': 'path7_7', 'filename': 'filename7_7', 'optype': '7_7', 'url': 'url7_7'},
                                     {'path': 'path7_8', 'filename': 'filename7_8', 'optype': '7_8', 'url': 'url7_8'}])
    xx = add_detail_for_app_ver('2.1.7', [{'path': 'path7_9', 'filename': 'filename7_9', 'optype': '7_9', 'url': 'url7_9'}])
    print xx, type(xx)
    '''

    print '=============111'
    print get_detail_by_app_ver('2.1.1')
    print '=============222'
    print get_detail_by_app_ver('2.1.7')
    print '=============333'
    print get_all_details_from_app_ver('2.1.1')
